import { getToken, setToken } from './auth'
import qs from 'qs'
import axios from 'axios'
import { Message } from 'element-ui'

export const $http = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})

$http.postOrJson = (url, params) => {
  return $http.post(url, params, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

$http.putOrJson = (url, params) => {
  return $http.put(url, params, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

$http.deleteOrJson = (url, params) => {
  return $http.delete(url, {
    data: params,
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

$http.interceptors.request.use(
  (config) => {
    const contentType = config.headers['Content-Type']

    if (config.data && contentType) {
      // 处理post请求
      // 发送json类型
      if (
        contentType.indexOf('application/json') >= 0 &&
                    typeof config.data === 'object'
      ) {
        config.data = JSON.stringify(config.data) // 转JSON字符串
      }

      // 发送form类型
      if (
        contentType.indexOf('application/x-www-form-urlencoded') >=
                    0
      ) {
        config.data = qs.stringify(config.data) // 用qs处理data
      }
    }
    config.headers['X-Token'] = getToken()
    return config
  },
  (error) => {
    // Do something with request error
    Promise.reject(error)
  }
)

// respone拦截器
$http.interceptors.response.use(
  (response) => {
    // 获取刷新的返回的TOKEN
    const headers = JSON.stringify(response.headers)
    const headersData = JSON.parse(headers)
    const token = headersData['x-auth-token']
    if (token) {
      // 将续期的TOKEN存起来
      setToken(token)
    }

    const res = response.data

    if (res.code === 403 || res.code === 401) {
      // session过期
      sessionStorage.setItem('login', null) //
      // removeToken();
      Message({
        showClose: true,
        message: res.data,
        type: 'error',
        duration: 500
      })
      return Promise.reject(new Error('未登录'))
    } else if (res.code === -1) {
      Message({
        showClose: true,
        message: res.data,
        type: 'error'
      })
      return Promise.reject(new Error('未登录'))
    }

    return res.body
  },
  (error) => {
    if (
      error.response.data.code === 403 ||
                error.response.data.code === 401
    ) {
      sessionStorage.setItem('login', null) //
      Message({
        showClose: true,
        message: error.response.data.message,
        type: 'error',
        duration: 1000
      })
    } else if (error.response.status === 404) {
      Message({
        message: '404页面找不到',
        type: 'error',
        showClose: true
      })
    } else {
      Message({
        message: error.response.data.message,
        type: 'error',
        showClose: true
      })
    }
    return Promise.reject(error)
  }
)

export default {
  install (Vue) {
    Object.defineProperty(Vue.prototype, '$http', {
      value: $http
    })
  }
}
